package com.zhenxiang.juc.readwritelock;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author : James
 * @Create : 2021-12-22-16:25
 * @Description :
 *
 *  读写锁
 *  包含 ：
 *  独占锁(写锁) 一次只能被一个线程占有
 *  共享锁(读锁) 多个线程可以同时占有
 *  读-读     可以同时共存
 *  读-写     不能同时共存
 *  写-写     不能同时共存
 *
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyLockCache cache = new MyLockCache();
        // 写入
        for (int i = 0; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                cache.put(String.valueOf(temp),temp);
            },String.valueOf(i)).start();
        }

        // 读取
        for (int i = 0; i <= 5; i++) {
            final int temp = i;
            new Thread(() -> {
                cache.get(String.valueOf(temp));
            }, String.valueOf(i)).start();
        }
    }
}


// 自定义 加锁缓存
class MyLockCache {

    private volatile Map<String,Object> map = new HashMap<>();

    // 读写锁 更细粒度的 锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 存  只允许一个线程操作
    public void put(String key, Object value) {
        // 获取写锁
        Lock lock = readWriteLock.writeLock();
        // 加锁
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入key==" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入key OK==");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }

    }

    // 取  读 所有线程都可以读取
    public void get(String key) {
        // 获取读锁
        Lock lock = readWriteLock.readLock();
        // 加锁
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取key==" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取key OK==");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }

    }

}



// 自定义普通 缓存
class MyCache {

    private volatile Map<String,Object> map = new HashMap<>();

    // 存
    public void put (String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入key=="+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入key OK==");
    }

    // 读
    public void get (String key) {
        System.out.println(Thread.currentThread().getName()+"读取key=="+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取key OK==");
    }



}
